package com.demo2;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: fzykd
 * Date: 2022-12-21
 * Time: 22:14
 */
class MyThreadPool{
    private BlockingQueue<Runnable> queue = new LinkedBlockingQueue<>();

    //描述一个线程 工作线程就是从任务队列中取数据
    static class Worker extends Thread{
        private BlockingQueue<Runnable> queue = null;

        public Worker(BlockingQueue<Runnable> queue) {
            this.queue = queue;
        }

        public void run(){
            //拿到上面的任务队列
            while (true){
                //循环的取获取任务队列中的任务
                //这里如果队列为空 就直接阻塞 如果队列非空 获取到里面的内容
                try {
                    Runnable runnable = queue.take();
                    //获取之后 就执行任务
                    runnable.run();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }

    }
    //4.创建一个数据结构来组织若干线程
    private List<Thread> workers = new ArrayList<>();

    public MyThreadPool(int n){
        //在构造方法中 创建若干线程 放到上述队列中
        for (int i = 0; i < n; i++) {
            com.Demo1.MyThreadPool.Worker worker = new com.Demo1.MyThreadPool.Worker(queue);
            worker.start();
            workers.add(worker);
        }
    }

    //创建一个方法 是程序员放任务到线程池中
    public void submit(Runnable runnable){
        try {
            queue.put(runnable);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}


//自主实现一个线程池
public class TestDemo6 {
    public static void main(String[] args) {
        MyThreadPool myThreadPool = new MyThreadPool(10);
        for (int i = 0; i < 100; i++) {
            myThreadPool.submit(new Runnable() {
                @Override
                public void run() {
                    System.out.println("hahha");
                }
            });
        }
    }
}
